package vn.orderonline.com.core.business.temporaryorder;

import java.util.ArrayList;
import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import vn.orderonline.com.core.business.dto.TemporaryDrinkBasketDto;
import vn.orderonline.core.dao.entity.TemporaryDrinkBasket;
import vn.orderonline.core.dao.entity.TemporaryDrinkBasketId;
import vn.orderonline.core.dao.temporaryorder.TemporaryDrinkBasketDao;

@Service
@Transactional
public class TemporaryDrinkBasketImpl implements ITemporaryDrinkBasket {
	
	@Autowired
	private TemporaryDrinkBasketDao temporaryDrinkBasketDao;

	@Override
	public void addDrink(Integer restaurantId, Integer drinkId, String drinkName, Float price) {
		TemporaryDrinkBasket temporaryDrinkBasket = temporaryDrinkBasketDao.find(new TemporaryDrinkBasketId(restaurantId, drinkId));
		if (temporaryDrinkBasket != null) {
			temporaryDrinkBasket.setAmount(temporaryDrinkBasket.getAmount() + 1);
			temporaryDrinkBasketDao.save(temporaryDrinkBasket);
		} else {
			temporaryDrinkBasket = new TemporaryDrinkBasket();
			temporaryDrinkBasket.setId(new TemporaryDrinkBasketId(restaurantId, drinkId));
			temporaryDrinkBasket.setDrinkName(drinkName);
			temporaryDrinkBasket.setPrice(price);
			temporaryDrinkBasket.setAmount(1);
			temporaryDrinkBasketDao.save(temporaryDrinkBasket);
		}
	}

	@Override
	public List<TemporaryDrinkBasketDto> getAllDrinks() {
		List<TemporaryDrinkBasket> listItem = temporaryDrinkBasketDao.findAll();
		if (!listItem.isEmpty()) {
			List<TemporaryDrinkBasketDto> list = new ArrayList<>();
			TemporaryDrinkBasketDto dto = null;
			for (TemporaryDrinkBasket tem : listItem) {
				dto = new TemporaryDrinkBasketDto();
				dto.setRestaurantId(tem.getId().getRestaurantId());
				dto.setDrinkId(tem.getId().getDrinkId());
				dto.setDrinkName(tem.getDrinkName());
				dto.setPrice(tem.getPrice() * tem.getAmount());
				dto.setAmount(tem.getAmount());
				list.add(dto);
			}
			return list;
		}
		return null;
	}

	@Override
	public Float calculateDrinkPrice() {
		List<TemporaryDrinkBasket> list = temporaryDrinkBasketDao.findAll();
		Float count = 0F;
		if (!list.isEmpty()) {
			for (TemporaryDrinkBasket tem : list) {
				count += tem.getPrice() * tem.getAmount();
			}
		}
		return count;
	}

	@Override
	public void removeDrinkBasket(Integer restaurantId, Integer drinkId) {
		TemporaryDrinkBasket temporaryDrinkBasket = temporaryDrinkBasketDao.find(new TemporaryDrinkBasketId(restaurantId, drinkId));
		if (temporaryDrinkBasket != null) {
			if (temporaryDrinkBasket.getAmount() > 1) {
				temporaryDrinkBasket.setAmount(temporaryDrinkBasket.getAmount() - 1);
				temporaryDrinkBasketDao.save(temporaryDrinkBasket);
			} else {
				temporaryDrinkBasketDao.delete(temporaryDrinkBasket);
			}
		}
		
	}

}
